package com.nengjiang.wsplayer.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.nengjiang.wsplayer.oksocket.OkManager;
import com.xuhao.didi.core.utils.SLog;

import java.util.Timer;
import java.util.TimerTask;

public class HeartbeatService extends Service {

    public static final String TAG = "HeartbeatService";

    private volatile boolean isStop = false;

    private int interval;
    private Timer timer;

    public HeartbeatService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        SLog.e("HeartbeatService onStartCommand");
        if (intent != null) {
            interval = intent.getIntExtra("interval", 10);
        }

        if (timer != null) {
            return START_STICKY;
        }

        timer = new Timer();
        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                boolean connecting = OkManager.getInstance().isConnecting();
                SLog.e("HeartbeatService connecting");
                if (connecting) {
                    OkManager.getInstance().heartOnce();

                }
            }
        };

        timer.schedule(task, 0, interval * 1000);

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
        super.onDestroy();
    }

}